<template>
  <div class="property-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">房屋状态管理系统</h1>
	            <p class="sub-title">每一套房屋的管理记录，都是对居住权益的守护；每一次信息的精准更新，都是对生活品质的负责，让居住更放心</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框：优化标题和关闭逻辑 -->
    <el-dialog
      v-model="dialogVisible"
      title="房产详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="房产信息" direction="vertical" :column="4" :model="message" border>
        <el-descriptions-item label="ID" :span="2">{{ message.id }}</el-descriptions-item>
        <el-descriptions-item label="建筑编号" :span="2">{{ message.buildingNumber }}</el-descriptions-item>
        <el-descriptions-item label="房产编码" :span="2">{{ message.propertyCode }}</el-descriptions-item>
        <el-descriptions-item label="房间号" :span="2">{{ message.roomNumber }}</el-descriptions-item>
        <el-descriptions-item label="业主名称" :span="2">{{ message.ownerName }}</el-descriptions-item>
        <el-descriptions-item label="联系方式" :span="2">{{ message.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="面积" :span="2">{{ message.area }}</el-descriptions-item>
        <el-descriptions-item label="房间数量" :span="2">{{ message.numberOfRooms }}</el-descriptions-item>
        <el-descriptions-item label="单元号" :span="2">{{ message.unit }}</el-descriptions-item>
        <el-descriptions-item label="楼层" :span="2">{{ message.floorNumber }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="4">{{ message.description }}</el-descriptions-item>
        <el-descriptions-item label="入住时间" :span="2">{{ formatDate(message.moveInDate) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框：添加表单验证、优化标题 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑房产"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="建筑编号" prop="buildingNumber">
              <el-input v-model.number="ruleForm.buildingNumber" type="number"></el-input>
            </el-form-item>
            <el-form-item label="房产编码" prop="propertyCode">
              <el-input v-model="ruleForm.propertyCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="ruleForm.roomNumber"></el-input>
            </el-form-item>
            <el-form-item label="业主名称" prop="ownerName">
              <el-input v-model="ruleForm.ownerName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="ruleForm.contactInfo"></el-input>
            </el-form-item>
            <el-form-item label="面积" prop="area">
              <el-input v-model.number="ruleForm.area" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间数量" prop="numberOfRooms">
              <el-input v-model.number="ruleForm.numberOfRooms" type="number"></el-input>
            </el-form-item>
            <el-form-item label="单元号" prop="unit">
              <el-input v-model="ruleForm.unit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼层数" prop="floorNumber">
              <el-input v-model.number="ruleForm.floorNumber" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入住时间" prop="moveInDate">
              <el-date-picker
                v-model="ruleForm.moveInDate"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateSubmit()">确定</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 新增对话框：添加表单验证、优化标题 -->
    <el-dialog
      v-model="dialogVisible2"
      title="新增房产"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="建筑编号" prop="buildingNumber" required>
              <el-input v-model.number="addForm.buildingNumber" type="number"></el-input>
            </el-form-item>
            <el-form-item label="房产编码" prop="propertyCode" required>
              <el-input v-model="addForm.propertyCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber" required>
              <el-input v-model="addForm.roomNumber"></el-input>
            </el-form-item>
            <el-form-item label="业主名称" prop="ownerName" required>
              <el-input v-model="addForm.ownerName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo" required>
              <el-input v-model="addForm.contactInfo"></el-input>
            </el-form-item>
            <el-form-item label="面积" prop="area" required>
              <el-input v-model.number="addForm.area" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间数量" prop="numberOfRooms" required>
              <el-input v-model.number="addForm.numberOfRooms" type="number"></el-input>
            </el-form-item>
            <el-form-item label="单元号" prop="unit" required>
              <el-input v-model="addForm.unit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼层数" prop="floorNumber" required>
              <el-input v-model.number="addForm.floorNumber" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入住时间" prop="moveInDate">
              <el-date-picker
                v-model="addForm.moveInDate"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSubmit">提交</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 数据操作区：优化顶部布局，使按钮更紧凑对齐 -->
    <el-row>
	<el-row style="width: 100%;">
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="7">
          <el-input 
            placeholder="输入房产编码进行查询" 
            v-model="propertyCode" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="sortField" 
            placeholder="选择排序字段" 
            style="width: 100%;"
          >
            <el-option label="ID" value="id"></el-option>
            <el-option label="建筑编号" value="buildingNumber"></el-option>
            <el-option label="房产编码" value="propertyCode"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="info" 
            @click="toggleSortOrder" 
            style="width: 100%;"
          >
            {{ sortOrder === 'asc' ? '升序' : '降序' }}
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="sortTable" 
            style="width: 100%;"
          >
            排序
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            icon="el-icon-plus" 
            @click="openDetails2" 
            style="width: 100%;"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
	  </el-row>
      
      <!-- 表格部分（仅展示修改的核心代码） -->
      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="buildingNumber" label="建筑编号" width="100" align="center"></el-table-column>
        <el-table-column prop="propertyCode" label="房产编码" width="150" align="center"></el-table-column>
        <el-table-column prop="roomNumber" label="房间号" width="100" align="center"></el-table-column>
        <el-table-column prop="ownerName" label="业主名称" width="120" align="center"></el-table-column>
        <el-table-column prop="contactInfo" label="联系方式" width="120" align="center"></el-table-column>
        <el-table-column prop="area" label="面积" width="80" align="center"></el-table-column>
        <el-table-column prop="numberOfRooms" label="房间数量" width="100" align="center"></el-table-column>
        <el-table-column prop="unit" label="单元号" width="80" align="center"></el-table-column>
        <el-table-column prop="floorNumber" label="楼层数" width="80" align="center"></el-table-column>
        <el-table-column prop="moveInDate" label="入住时间" width="120" align="center" :formatter="formatDate"></el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <!-- 用 Flex 布局让按钮横向排列，并通过 gap 控制间距 -->
            <div class="operation-buttons">
              <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetails(scope.row)">查看</el-button>
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openDetails1(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteProperty(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页：保持原有逻辑 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElDialog, ElDescriptions, ElDescriptionsItem, ElForm, ElFormItem, ElInput, ElRow, ElCol, ElDatePicker, ElButton, ElTable, ElTableColumn, ElPagination, ElSelect, ElOption, ElLoading } from 'element-plus'

const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const propertyCode = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])
const ruleFormRef = ref(null)
const addFormRef = ref(null)

// 排序相关变量
const sortField = ref('id') // 排序字段：id、buildingNumber、propertyCode
const sortOrder = ref('asc') // 排序方向：asc（升序）、desc（降序）

// 表单验证规则
const rules = reactive({
  buildingNumber: [
    { required: true, message: '请输入建筑编号', trigger: 'blur' },
    { type: 'number', message: '建筑编号必须为数字', trigger: 'blur' }
  ],
  propertyCode: [
    { required: true, message: '请输入房产编码', trigger: 'blur' }
  ],
  roomNumber: [
    { required: true, message: '请输入房间号', trigger: 'blur' }
  ],
  ownerName: [
    { required: true, message: '请输入业主名称', trigger: 'blur' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' },
    { type: 'number', message: '面积必须为数字', trigger: 'blur' }
  ],
  numberOfRooms: [
    { required: true, message: '请输入房间数量', trigger: 'blur' },
    { type: 'number', message: '房间数量必须为数字', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单元号', trigger: 'blur' }
  ],
  floorNumber: [
    { required: true, message: '请输入楼层数', trigger: 'blur' },
    { type: 'number', message: '楼层数必须为数字', trigger: 'blur' }
  ]
})

// 详情数据对象
const message = reactive({
  id: '',
  buildingNumber: '',
  propertyCode: '',
  roomNumber: '',
  ownerName: '',
  contactInfo: '',
  area: '',
  numberOfRooms: '',
  unit: '',
  floorNumber: '',
  description: '',
  moveInDate: '',
})

// 编辑表单数据
const ruleForm = reactive({
  id: '',
  buildingNumber: null,
  propertyCode: '',
  roomNumber: '',
  ownerName: '',
  contactInfo: '',
  area: null,
  numberOfRooms: null,
  unit: '',
  floorNumber: null,
  description: '',
  moveInDate: null,
})

// 新增表单数据
const addForm = reactive({
  buildingNumber: null,
  propertyCode: '',
  roomNumber: '',
  ownerName: '',
  contactInfo: '',
  area: null,
  numberOfRooms: null,
  unit: '',
  floorNumber: null,
  description: '',
  moveInDate: null,
})

// 修改日期格式化函数，使其兼容两种调用方式
// 日期格式化：兼容「表格formatter」和「详情对话框」两种调用场景
const formatDate = (param1, param2, param3) => {
  let value = '';
  // 场景1：表格formatter调用（传递3个参数：row, column, cellValue）
  if (param3 !== undefined) { 
    value = param3; // 直接取第三个参数（单元格原始值）
  } 
  // 场景2：详情对话框调用（仅传递1个参数：messageForm.hireDate）
  else { 
    value = param1; // 取第一个参数（直接传入的日期值）
  }

  // 过滤无效值
  if (!value || value === 'null' || value === 'undefined') return '';

  // 统一转换为Date对象（兼容字符串、时间戳）
  let date;
  if (typeof value === 'number') {
    date = new Date(value); // 处理时间戳（如1725686400000）
  } else {
    date = new Date(value); // 处理字符串（如'2024-09-07'）
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) return '无效日期';

  // 格式化为「YYYY-MM-DD」
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 查看详情
function openDetails(row) {
  dialogVisible.value = true
  Object.keys(message).forEach(key => {
    message[key] = row[key] ?? ''
  })
}

// 打开编辑对话框
function openDetails1(row) {
  dialogVisible1.value = true
  Object.keys(ruleForm).forEach(key => {
    if (key === 'moveInDate' && row[key]) {
      ruleForm[key] = new Date(row[key])
    } else {
      ruleForm[key] = row[key] ?? (typeof ruleForm[key] === 'number' ? null : '')
    }
  })
}

// 打开新增对话框
function openDetails2() {
  dialogVisible2.value = true
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'moveInDate' ? null : (typeof addForm[key] === 'number' ? null : '')
  })
}

function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val) {
  currentPage.value = val
}

function changeDate(date) {
  if (!date) return '';
  const d = new Date(date);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

// 更新房产（带表单验证）
function updateSubmit() {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return;
    if (typeof ruleForm.moveInDate !== 'string') {
      ruleForm.moveInDate = changeDate(ruleForm.moveInDate);
    }
    const loading = ElLoading.service({ text: '修改中...' })
    post('/sc/property/updateById', ruleForm, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('修改成功！')
        dialogVisible1.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    })
  })
}

// 新增房产（带表单验证）
function addSubmit() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    if (typeof addForm.moveInDate !== 'string') {
      addForm.moveInDate = changeDate(addForm.moveInDate);
    }
    const loading = ElLoading.service({ text: '新增中...' })
    post('/sc/property/add', addForm, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('添加成功！')
        dialogVisible2.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 删除房产
function deleteProperty(row) {
  ElMessageBox.confirm(`确定删除房产 ${row.propertyCode} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/property/deleteById', { id: row.id }, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('删除成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

// 搜索房产
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  if (!propertyCode.value.trim()) {
    fetchTableData()
    loading.close()
    return
  }
  post('/sc/property/searchByCode', { code: propertyCode.value }, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success(`找到 ${res.data.length} 条记录`)
    } else {
      tableData.value = []
      ElMessage.warning('未找到匹配记录')
    }
  })
}

// 切换排序方向（升序/降序）
function toggleSortOrder() {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
}

// 执行表格排序
function sortTable() {
  tableData.value.sort((rowA, rowB) => {
    let valueA, valueB;
    // 根据选择的排序字段获取对应值
    if (sortField.value === 'id') {
      valueA = Number(rowA.id);
      valueB = Number(rowB.id);
    } else if (sortField.value === 'buildingNumber') {
      valueA = Number(rowA.buildingNumber);
      valueB = Number(rowB.buildingNumber);
    } else if (sortField.value === 'propertyCode') {
      valueA = rowA.propertyCode;
      valueB = rowB.propertyCode;
    } else {
      return 0; // 无有效排序字段，不排序
    }
    // 根据排序方向决定排序逻辑
    if (sortOrder.value === 'asc') {
      return valueA > valueB ? 1 : -1; // 升序：小 -> 大
    } else {
      return valueA < valueB ? 1 : -1; // 降序：大 -> 小
    }
  });
}

// 获取所有房产（带加载状态）
function fetchTableData() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/property/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  })
}

onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}
	
.operation-buttons {
  display: flex;
  gap: 4px; /* 最小化按钮间距 */
}

/* 自定义超小按钮样式（比mini更小） */
.operation-buttons .el-button--mini {
  padding: 1px 6px; /* 减小内边距 */
  font-size: 12px; /* 缩小字体（如果保留文字） */
  height: 24px; /* 降低按钮高度 */
  min-width: auto; /* 取消最小宽度限制 */
}
.property-container {
  width: auto;
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

/* 统一按钮间距和表单样式 */
.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}
.el-form {
  padding: 10px;
}
</style>